# -*- coding:utf-8 -*-
import requests
import json

from configs.config import CONFIG_PATH
from tools.common import read_config, w_logging


def restful_api(url, method, args=None ,TK=None ,value_json=None):
    """
     *函数说明*: 执行Restful API请求   根据自己web的接口自定义
    """
    ret = ''
    headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
               "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
               "Cookie": "TK={}".format(TK)}
    s = requests.session()
    config_path = CONFIG_PATH
    host_url = read_config(config_path, 'WEB', 'HOST')
    url = host_url + url
    for i in range(5):
        try:
            if method == 'post':
                if value_json:
                    for key in args:
                        v = args[key]
                        args[key] = json.dumps(v)
                    ret = s.post(url, data=args, headers = headers, timeout=120)
                else:
                    ret = s.post(url, data=args, headers = headers, timeout=120)
            elif method == 'get':
                ret = s.get(url, data=args, headers = headers, timeout=120)
            log, log_err = w_logging()
            log.logger.info(
                '--url:{}  --请求方式：{}  --请求参数：{} --接口返回code: {} --接口返回信息：{}'.format(url, method, args, ret.status_code,
                                                                                   ret.content.decode('utf-8')))
            return ret.status_code, ret.content.decode('utf-8')
        except Exception as e:
            log, log_err = w_logging()
            log_err.logger.info('--url:{} --请求方式：{} --请求参数：{} --错误信息{}'.format(url, method, args, e))


def login_web():
    username = read_config(CONFIG_PATH, 'WEB', 'USERNAME')
    password = read_config(CONFIG_PATH, 'WEB', 'PASSWORD')
    # 自行封装登入接口调用即可
    print(f'使用配置文件config.ini 户名密码登入 username: {username}, password {password}')


def get_api():
    # 业务接口根据业务需求增加
    pass